<?php
/**
 * Created by PhpStorm.
 * User: shaowei
 * Date: 2019/5/11
 * Time: 下午3:25
 */

namespace App\Lib;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use App\Http\Model\SystemConfig;
use Illuminate\Support\Facades\Redis;

use Qiniu\Auth;
use Qiniu\Sms\Sms;

class SendSms
{
    private $auth;
    private $client;

    public function __construct()
    {
        $accessKey = config("qiniu.access_key");
        $secretKey = config("qiniu.secret_key");

        $this->auth = new Auth($accessKey, $secretKey);
        $this->client = new Sms($this->auth);
    }

    /**
     * 发送短信 七牛
     *
     * @param string|array $mobiles 手机号
     * @param string $code 验证码
     * @return array
     */
    public function qiniuSendVerify($mobiles, $code, $ccode = '86')
    {
        if (!is_array($mobiles)) {
            if ($ccode != '86') {
                $mobiles = $ccode . $mobiles;
            }
            $mobiles = [$mobiles];
        }
        $templateId = config("qiniu.template_id");
        $code = array('code' => $code);

        list($ret, $err) = $this->client->sendMessage($templateId, $mobiles, $code);
        write_log("SendSms", "qiniuSendVerify", [$mobiles, $code, $ret, $err]);
        if ($err !== null) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 发送短信 腾域
     *
     * @param string $mobiles 手机号
     * @param string $code 验证码
     * @return array
     */
    public function tengyuSendVerify($mobiles, $code, $ccode = '86')
    {
        if ($ccode != '86') {
            $mobiles = $ccode . $mobiles;
        }

        $url = config("tengyu.url");
        $userName = config("tengyu.userName");
        $password = config("tengyu.password");
        $timestamp = time() . '000';
        $sign = md5($userName . $timestamp . MD5($password));

        $message = [
            'phone' => $mobiles,
            'content' => '【唯凯网络】您的验证码为：' . $code . '，该验证码5分钟内有效，请勿泄露给他人。',
        ];
        $body = [
            'userName' => $userName,
            'messageList' => [
                (object)$message,
            ],
            'timeStamp' => $timestamp,
            'sign' => $sign,
        ];

        $res = curl_request($url, $body, 'json', 'POST');
        write_log("SendSms", "tengyuSendVerify", [$mobiles, $code, $res]);
        $res = json_decode($res, true);
        if (isset($res['code']) && $res['code']==0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 群发短信
     * @param array $phonelist 手机数据
     * @param string $content 发送文案
     * @return bool
     */
    public function tengyuSendAllSms($phonelist = array(), $content = '')
    {
        if (empty($phonelist) || empty($content)) {
            return false;
        }
        $url = config("tengyu.AllSmsurl");
        $userName = config("tengyu.allsmsName");
        $password = config("tengyu.allsmsPwd");
        $timestamp = time() . '000';
        $content = '【唯凯网络】'.$content;
        $sign = md5($userName . $content . $timestamp . MD5($password));

        //发送主体
        $body = [
            'userName' => $userName,
            'content' => $content,
            'phoneList' => $phonelist,
            'timeStamp' => $timestamp,
            'sign' => $sign,
        ];

        $res = curl_request($url, $body, 'json', 'POST');
        write_log("SendSms", "tengyuSendAllSms", [$phonelist, '', $res]);
        $res = json_decode($res, true);
        if (isset($res['code']) && $res['code']==0) {
            return $res;
        } else {
            return false;
        }
    }

    /**
     * 获取回执状态
     *
     * @return bool|mixed
     */
    public function tengyuSendAllStatus()
    {
        $url = config("tengyu.getReportUrl");
        $userName = config("tengyu.allsmsName");
        $password = config("tengyu.allsmsPwd");
        $timestamp = time() . '000';
        $sign = md5($userName . $timestamp . MD5($password));
        //发送主体
        $body = [
            'userName' => $userName,
            'timeStamp' => $timestamp,
            'sign' => $sign,
        ];
        $res = curl_request($url, $body, 'json', 'POST');
        write_log("SendSms", "tengyuSendAllStatus", $res);
        $res = json_decode($res, true);
        if (isset($res['code']) && $res['code']==0) {
            return $res;
        } else {
            return false;
        }
    }

    /**
     * weiWeb短信发送
     *
     * @param [type] $phone
     * @param [type] $smsCode
     * @return void
     */
    public function WeiWebSendAllSms($phone, $smsCode) {
        $config = config("sms");

        $data['account'] = $config['weiweb']['account'];// 账号
        $data['pswd'] = $config['weiweb']['pswd'];// 密码
        $data['mobile'] = $phone;// 手机号
        $data['msg']= '【唯凯网络】您的验证码是：'.$smsCode.'，五分钟内有效。';// 签名
        $data['needstatus'] ="true";
        $data['resptype'] ="json";
        $url='https://www.weiwebs.cn/msg/HttpBatchSendSM';
    
        $res = curl_request($url, $data, 'urlencoded', 'POST');
        write_log("SendSms", "WeiWebSendAllSms", [$phone, $smsCode, $res]);
        return $res;
    }

    /**
     * sp短信发送
     *
     * @param [type] $phone
     * @param [type] $smsCode
     * @return bool
     */
    public function spSendSingleSms($phone, $smsCode) {
        $config = new SystemConfig();
        $sms_channel = $config->getSmsChannel();
        if ($sms_channel == 1) {
            return $this->submailXSms($phone, $smsCode);
        }

        $config = config("sms");
        $sp_id = $config['sp']['sp_id'];// 密码
        $pwd = $config['sp']['pwd'];// 密码

        $content = '【典优网络】您的验证码是'.$smsCode.'，该验证码5分钟内有效，请勿泄露于他人。';

        //短信发送
        $postData = array(
            'sp_id' => $sp_id,
            'mobile' => $phone,
            'content' => $content,
        );

        $usePassword = true;
        //如果是使用得密码发送
        if ($usePassword) {
            $postData['password'] = md5($pwd);
        } else {
            $postData['signature'] = $this->spSign($postData, 'POST', $pwd);
        }

        $url='http://110.40.226.85:9511/api/send-sms-single';

        $res = curl_request($url, $postData, 'urlencoded', 'POST');
        write_log("SendSms", "spSendSingleSms", [$phone, $smsCode, $res]);

        $res = json_decode($res, true);
        if (isset($res['code']) && $res['code']==0) {
            return true;
        } else {
            return false;
        }
    }

    protected function spSign($data, $method, $password)
    {
        ksort($data);

        $uri = $method . '&' . urlencode('/') . '&' . preg_replace(['/\+/', '/\*/', '/%7E/'], ['%20', '%2A', '~'], http_build_query($data));

        return base64_encode(hash_hmac("sha1", $uri, $password));
    }

    /**
     * 短信模板发送
     */
    public function submailXSms($phone, $code)
    {
        $config = config("sms");
        $app_id = $config['submail']['app_id'];
        $app_key = $config['submail']['app_key'];

        $projectId = $config['submail']['project_id'];

        $url = 'https://api-v4.mysubmail.com/sms/xsend';
        $params = [
            'appid' => $app_id,
            'signature' => $app_key,
            'to' => $phone,
            'project' => $projectId,
            'vars' => json_encode(['code' => $code]),
        ];
        $response = curl_request($url, $params);

        $res = json_decode($response, true);
        if ($res['status'] == 'success') {
            return true;
        }

        write_log("SendSms", "submailXSms", [$phone, $res]);
        return false;
    }
}